package com.wang.spring.handler;


import com.alibaba.fastjson.JSONObject;
import com.wang.just_read.JustRead;
import com.wang.utils.IOUtils;
import com.wang.utils.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class JustReadHandler extends HandlerInterceptorAdapter {

    private JustRead justRead;

    public JustReadHandler(DataSource dataSource) {
        this.justRead = new JustRead();
        this.justRead.setDataSource(dataSource);
    }

    public void init(Map<String, String> nameAndSql) throws SQLException {
        for (Map.Entry<String, String> entry : nameAndSql.entrySet()) {
            this.justRead.register(entry.getKey(), entry.getValue());
        }
    }

    public void init(File file) throws IOException, SQLException {
        String config = IOUtils.readAll(file);
        for (Map.Entry<String, Object> entry : JSONObject.parseObject(config).getInnerMap().entrySet()) {
            this.justRead.register("/" + entry.getKey(), (String) entry.getValue());
        }
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getServletPath();
        if (!justRead.contains(url)) return super.preHandle(request, response, handler);

        String body = IOUtils.readAll(request.getInputStream(), request.getContentLength());

        List<Map<String, Object>> r = this.justRead.execute(url, JSONObject.parseObject(body, Map.class));
        String rStr = "{\"code\":0,\"data\":" + JSONObject.toJSONString(r) + "}";
        response.getWriter().write(rStr);
        return false;
    }
}
